﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KulaQ.Models;
using Microsoft.AnalysisServices.AdomdClient;

namespace KulaQ.Models
{
    public class PredictionModel : List<PredictionViewItem>
    {
        
    }
    public class PredictionViewItem
    {
        public decimal Probability { get; set; }
        public string Prediction { get; set; }
        public string PersonName { get; set; }
    }
}

namespace KulaQ.Helpers
{

    public class DmxHelper
    {
        AdomdConnection conn = new AdomdConnection();
        AdomdCommand cmd = new AdomdCommand();

        public DmxHelper()
        {
            Initialize();
        }

        private void Initialize()
        {
            conn.ConnectionString = "Data Source=localhost; Catalog=DM_Basic";
            conn.Open();

            cmd.Connection = conn;
        }

        public PredictionModel DmxQuery()
        {
            var table = new PredictionModel();

            cmd.CommandText = DmxString;

            AdomdDataReader dataReader = cmd.ExecuteReader();

            for (int i = 0; i < 100 && dataReader.Read(); i++)
            {
                var col = new PredictionViewItem();
                col.PersonName = dataReader.GetString(1) + " " + dataReader.GetString(2);
                col.Prediction = dataReader.GetString(0);
                col.Probability = dataReader.GetDecimal(3);
                table.Add(col);
            }

            return table;
        }

        public bool CreateModel()
        {

            return false;
        }
        public static string DmxString
        {
            get
            {
                return @"
SELECT
  [TM_Decision_Tree].[Bike Buyer],
  t.[FirstName],
  t.[LastName],
  PredictProbability([TM_Decision_Tree].[Bike Buyer])
From
  [TM_Decision_Tree]
PREDICTION JOIN
  OPENQUERY([Adventure Works DW2008R2],
    'SELECT
      [FirstName],
      [LastName],
      [MaritalStatus],
      [Gender],
      [YearlyIncome],
      [TotalChildren],
      [NumberChildrenAtHome],
      [HouseOwnerFlag],
      [NumberCarsOwned],
      (DATEDIFF(YYYY,[BirthDate], getdate())) AS [calcAge],
      [Unknown]
    FROM
      [dbo].[ProspectiveBuyer]
    ') AS t
ON
  [TM_Decision_Tree].[Marital Status] = t.[MaritalStatus] AND
  [TM_Decision_Tree].[Gender] = t.[Gender] AND
  [TM_Decision_Tree].[Yearly Income] = t.[YearlyIncome] AND
  [TM_Decision_Tree].[Total Children] = t.[TotalChildren] AND
  [TM_Decision_Tree].[Number Children At Home] = t.[NumberChildrenAtHome] AND
  [TM_Decision_Tree].[House Owner Flag] = t.[HouseOwnerFlag] AND
  [TM_Decision_Tree].[Number Cars Owned] = t.[NumberCarsOwned] AND
  [TM_Decision_Tree].[Age] = t.[calcAge] AND
  [TM_Decision_Tree].[Bike Buyer] = t.[Unknown]";
            }
        }
    }
}